package demo523;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class UpdateDemo {

    private static final String URL = "jdbc:mysql://localhost:3306/userdb";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "123456";

    public static void main(String[] args) {
        try {
            // 1. 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取连接
            try (Connection connection = DriverManager.getConnection(URL, DB_USERNAME, DB_PASSWORD)) {

                // 3. 编写 SQL 更新语句
                String sql = "UPDATE users SET username = ?, password = ? WHERE id = ?";

                // 4. 创建 PreparedStatement
                try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

                    // 5. 获取用户输入
                    Scanner scanner = new Scanner(System.in);

                    System.out.println("请输入要修改的用户ID：");
                    int id = scanner.nextInt();
                    scanner.nextLine(); // 清除换行符

                    System.out.println("请输入新的用户名：");
                    String newUsername = scanner.nextLine();

                    System.out.println("请输入新的密码：");
                    String newPassword = scanner.nextLine();

                    // 6. 设置参数
                    preparedStatement.setString(1, newUsername);
                    preparedStatement.setString(2, newPassword);
                    preparedStatement.setInt(3, id);

                    // 7. 执行更新
                    int rowsAffected = preparedStatement.executeUpdate();

                    if (rowsAffected > 0) {
                        System.out.println("用户信息更新成功！");
                    } else {
                        System.out.println("未找到对应ID的用户，更新失败。");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


